<template>
    <view style="background:#eee; min-height:100%;">
		<view class="body">
			<uni-search-bar :radius="100" v-model="searchContent" @confirm="search" :placeholder="searchPlaceholder"></uni-search-bar>
			<view v-if="type == 0">
				<view class="rowItem" v-for="item in searchUsers" :key="item.userId">
				    <image :src="item.userPhoto" class="leftImg"></image>
				    <text class="text" v-text="item.userNickname"></text>
					<button class="addBtn" @click="addFriend(item)" v-if="item.type == 2">添加</button>
					<text class="rightText" v-else-if="item.type == 1">等待验证</text>
				</view>
			</view>
			<view v-if="type == 1">
				<view class="rowItem" v-for="item in searchGroups" :key="item.userId">
				    <image :src="item.groupPhoto" class="leftImg"></image>
				    <text class="text" v-text="item.groupName"></text>
					<button class="addBtn" @click="addGroup(item)" v-if="item.type == 2">添加</button>
					<text class="rightText" v-else-if="item.type == 1">等待验证</text>
				</view>
			</view>
		</view>
		<view class="tabBar">
		    <image class="arrowleft" mode="heightFix" src="http://192.168.43.54:8002/images/icon/news/arrowleft.png" @touchend="back"></image>
		    <text v-text="title"></text>
		</view>
	</view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { uniSearchBar } from '@dcloudio/uni-ui'
export default {
	components: {
		uniSearchBar
	},
	data() {
		return {
			users: [],
			searchContent: '',
			searchUsers: [],
			type: -1,
			title: '',
			searchPlaceholder: '',
			searchGroups: []
		}
	},
	onLoad(option) {
		this.type = option.type
		if (this.type == 0) {
			this.title = '找人'
			this.searchPlaceholder = '输入手机号/昵称'
		} else {
			this.title = '找群'
			this.searchPlaceholder = '输入群号/群名称'
		}
	},
	methods: {
		back() {
		    uni.navigateBack({
		        delta: 1
		    })
		},
		searchUser() {
			this.searchUsers = []
			this.$axios.post('getUsersByPhone', this.qs.stringify({
				userPhone: this.searchContent
			}))
			.then(res => {
				if (res.data.status != -1 && res.data.data != null) {
					let user = {
						userId: res.data.data.userId,
						userNickname: res.data.data.userNickname,
						userPhoto: res.data.data.userPhoto,
						type: -1
					}
					this.pushTosearchUsers(user)
				}
			})
			.catch(err => {
				console.log(err)
			})
			
			this.$axios.post('getUsersByNickname', this.qs.stringify({
				userNickname: this.searchContent
			}))
			.then(res => {
				if (res.data.status != -1) {
					res.data.data.forEach(item => {
						let user = {
							userId: item.userId,
							userNickname: item.userNickname,
							userPhoto: item.userPhoto,
							type: -1
						}
						this.pushTosearchUsers(user)
					})
				}
			})
			.catch(err => {
				console.log(err)
			})
		},
		pushTosearchUsers(item) {
			this.$axios.post('hp/selectOneFriend', this.qs.stringify({
				userId: this.user.userId,
				friendId: item.userId
			}))
			.then(r1 => {
				if (r1.data.friend == null) {
					this.$axios.post('hp/selectOneVerification', this.qs.stringify({
						userId: this.user.userId,
						fromId: this.user.userId,
						toId: item.userId,
						verificationStatus: 0
					}))
					.then(r2 => {
						if (r2.data.status != -1) {
							if (r2.data.friendVerification != null) {
								// 1: 等待验证
								item.type = 1
								this.searchUsers.push(item)
							} else {
								// 2: 添加按钮
								item.type = 2
								this.searchUsers.push(item)
							}
						}
					})
					.catch(err => {
						console.log(err)
					})
				} else {
					// 3: 不显示
					item.type = 3
					this.searchUsers.push(item)
				}
			})
			.catch(err => {
				console.log(err)
			})
		},
		addFriend(user) {
			this.sendMessage({
				userId: this.user.userId,
				fromId: this.user.userId,
				toId: user.userId,
				verificationStatus: 0,
				option: 'add',
				verificationType: 0,
				nickname: user.nickname
			})
		},
		sendMessage(msg, callback) {
		    msg.type = 'verification'
		    if (this.mySocket.socketOpen) {
		        this.mySocket.socketTask.send({
		            data: JSON.stringify(msg),
                    success: () => {
						if (this.type == 0) {
							for (let i=0; i<this.searchUsers.length; i++) {
								if (this.searchUsers[i].userId == msg.toId) {
									this.searchUsers[i].type = 1
									break
								}
							}
						} else {
							for (let i=0; i<this.searchGroups.length; i++) {
								if (this.searchGroups[i].groupId == msg.groupId) {
									this.searchGroups[i].type = 1
									break
								}
							}
						}
						
						this.$axios.post('getUserById', this.qs.stringify({
							userId: msg.toId
						}))
						.then(res => {
							msg.headPhoto = res.data.data.userPhoto
							this.verifications.push(msg)
						})
						.catch(err => {
							console.log(err)
						})
                    }
		        })
		    } else {
		        // this.mySocket.socketMsgQueue.push(msg)
		    }
		    if (callback) callback()
		},
		search() {
			if (this.type == 0) this.searchUser()
			else this.searchGroup()
		},
		searchGroup() {
			this.$axios.post('selectGroupByIdOrName', this.qs.stringify({
				content: this.searchContent
			}))
			.then(res => {
				if (res.data.status != -1 && res.data.groups != null) {
					res.data.groups.forEach(g => {
						let group = {
							groupId: g.groupId,
							groupName: g.groupName,
							groupPhoto: g.groupPhoto,
							ownerId: g.ownerId,
							type: -1
						}
						this.pushTosearchGroups(group)
					})
				}
			})
			.catch(err => {
				console.log(err)
			})
		},
		pushTosearchGroups(group) {
			this.$axios.post('selectAllMember', this.qs.stringify({
				groupId: group.groupId
			}))
			.then(res => {
				if (res.data.status != -1) {
					let members = res.data.users
					let flag = false
					members.forEach(member => {
						if (member.userId == this.user.userId) {
							flag = true
						}
					})
					if (flag) {
						group.type = 3
						this.searchGroups.push(group)
					} else {
						this.$axios.post('selectGroupVerifications', this.qs.stringify({
							userId: this.user.userId,
							groupId: group.groupId,
							fromId: this.user.userId
						}))
						.then(r => {
							if (r.data.status != -1) {
								if (r.data.groupVerifications.length != 0) {
									group.type = 1
								} else {
									group.type = 2
								}
								this.searchGroups.push(group)
							}
						})
						.catch(e => {
							console.log(e)
						})
					}
				}
			})
			.catch(err => {
				console.log(err)
			})
		},
		addGroup(group) {
			this.sendMessage({
				userId: this.user.userId,
				fromId: this.user.userId,
				toId: group.ownerId,
				verificationStatus: 0,
				option: 'add',
				verificationType: 1,
				source: 'apply',
				groupId: group.groupId,
				groupPhoto: group.groupPhoto,
				groupName: group.groupName
			})
		}
	},
    computed: {
        ...mapState(['user', 'mySocket', 'verifications'])
    },
	catch: {
        searchUsers: {
            handler: newVal => {},
            immediate: true
        }
    }
}
</script>

<style>
.tabBar {
    text-align: center;
    font-size: 20px;
    background-color: rgb(0,170,254);
    padding: 3% 11px;
    position: fixed;
    width: 94%;
    color: white;
    top: 0;
    min-height: 30px;
}

.tabBar .arrowleft {
    width: 20px;
    height: 20px;
    position: absolute;
    top: 50%;
    left: 15px;
    transform: translateY(-50%);
}

.body {
    padding-top: 50px;
    overflow: hidden;
}

.rowItem {
    padding: 10px;
    border: 1px solid #eee;
    background-color: white;
    display: flex;
	position: relative;
}

.leftImg {
    height: 45px;
    width: 45px;
    border-radius: 5px;
    margin-right: 20px;
}

.text {
    line-height: 45px;
}

.rightText {
	line-height: 45px;
	position: absolute;
	right: 15px;
}

.addBtn {
	background-color: rgb(0,170,254);
	border-radius: 20px;
	font-size: 13px;
	height: 30px;
	line-height: 30px;
	width: 60px;
	position: absolute;
	top: 50%;
	right: 15px;
	transform: translateY(-50%);
}
</style>